#include <iostream>
#include <string.h>

using std::cout;
using std::endl;


void *operator new(size_t sz){
    cout<<"void *operator new(size_t)"<<endl;
    //用malloc申请未初始化空间
    void *pret=malloc(sz);
    return pret;
}
    
void operator delete(void *ptr){
    cout<<"void operator delete(void * ptr)"<<endl;
    free(ptr);
}

class Student{
public:
    Student(const char *name,int id)
    : _name(new char[strlen(name) + 1 ]())
    , _id(id)
    {
        cout<<"构造函数"<<endl;
        strcpy(_name,name);
    }
    
/*    static void *operator new(size_t sz){
        cout<<"void *operator new(size_t)"<<endl;
        //用malloc申请未初始化空间
        void *pret=malloc(sz);

        return pret;
    }
    
    static void operator delete(void *ptr){
        cout<<"void operator delete(void * ptr)"<<endl;
        free(ptr);
    }
*/
    void print() const{
        if(_name){
            cout<<_name<<endl;
            cout<<_id<<endl;
        }
    }

    void destroy(){
        //this->~Student(); 不行，因为只是析构函数，没有执行operator delete
        delete this;
    }

private:
    //把析构函数设为私有，此时栈对象就不能创建了
    ~Student(){
        if(_name){
            //delete this;  死循环
            delete []_name;
            _name=nullptr;
        }
        cout<<"已经释放"<<endl;
    }

private:
    char *_name;
    int _id;

};

void test(){
    
/*    Student stu=Student("xiaowang",4200);
    stu.print();
    cout<<endl;
*/
    Student *pstu=new Student("xiaohong",4201);
    pstu->print();
    cout<<endl;

    pstu->destroy();
    pstu=nullptr;

    pstu->destroy();
}

int main()
{   
    test();

    return 0;
}

